package com.atguigu.bigdata.chapter05.transform;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/9/2 10:26
 */
public class Flink14_Process_KeyBy_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(3);
        
        // 统计每个传感器的水位和
        env
            .readTextFile("input/sensor.txt")
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(
                        data[0],
                        Long.valueOf(data[1]),
                        Integer.valueOf(data[2])
                    );
                }
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
               Map<String, Integer> IdToSum=  new HashMap<>();
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    String key = ctx.getCurrentKey();
    
                    Integer sum = IdToSum.getOrDefault(key, 0);  // 从map只取值, 如果存在就返回, 否则返回0
                    
                    sum += value.getVc();
    
                    IdToSum.put(key, sum);
                    
                    out.collect(ctx.getCurrentKey() + " 的水位和: " + sum);
                }
            })
            .print();
          
            
           
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
process可以替换:
 map filter flatMap
 sum max min
   .....
 
 
 */